package com.swang.pms.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.swang.pms.model.constants.CommonConstants;
import com.swang.pms.web.servlet.ParameterRequestWrapper;

/**
 * MenuFilter.java
 * 
 * @description 菜单权限拦截控制
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
public class MenuFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        String menu = httpRequest.getParameter("m");
        String smenu = session.getAttribute(CommonConstants.MENU_KEY) == null ? ""
                : (String) session.getAttribute(CommonConstants.MENU_KEY);
        if (!StringUtils.isEmpty(menu)) {
            if (!menu.equals(smenu)) {
                session.setAttribute(CommonConstants.MENU_KEY, menu);
            }
        } else {
            menu = smenu;
        }
        Map<String, String[]> m = new HashMap<String, String[]>(httpRequest.getParameterMap());
        m.put("m", new String[] { menu });
        httpRequest = new ParameterRequestWrapper((HttpServletRequest) httpRequest, m);
        chain.doFilter(httpRequest, httpResponse);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}
